<?php
class OfferForm extends BaseForm {
  const FORM_NAME                     = 'frm';
  
  const FIELD_IS_MOVIE_NONEMPTY       = 'is_movie_nonempty';
  const FIELD_OFFER_CODE              = 'offer_code';
  const FILED_SCREEN_NO               = 'screen_no';
  const FIELD_CINEMA                  = 'cinema';
  const FIELD_MOVIE_TITLE             = 'movie_title';
  const FIELD_MOVIE_TRAILER_URL       = 'movie_trailer_url';
  const FIELD_VALID_FROM_D            = 'offer_from_d';
  const FIELD_VALID_FROM_T            = 'offer_from_t';
  const FIELD_VALID_TO_D              = 'offer_to_d';
  const FIELD_VALID_TO_T              = 'offer_to_t';
  const FIELD_SESSION_TIME_D          = 'session_time_d';
  const FIELD_SESSION_TIME_T          = 'session_time_t';
  const FIELD_TICKET_PRICE            = 'ticket_price';
  const FIELD_SEATS_COUNT             = 'seats_count';
  const FIELD_SEATS_FROM              = 'seats_from';
  const FIELD_SEATS_TO                = 'seats_to';
  const FIELD_CINEMA_NO               = 'cinema_no';
  const FIELD_ADDITIONAL_INFO         = 'additional_info';
  const FIELD_STATUS                  = 'status';

  const SORT_CODE                     = 'CODE';
  const SORT_CINEMA                   = 'CINEMA';
  const SORT_MOVIE                    = 'MOVIE';
  const SORT_VALID_FROM               = 'VALID_FROM';
  const SORT_VALID_TO                 = 'VALID_TO';
  const SORT_SESSION_TIME             = 'SESSION_TIME';
  const SORT_TICKET_PRICE             = 'TICKET_PRICE';
  const SORT_SEATS_COUNT              = 'SEATS_COUNT';
  const SORT_FILLED                   = 'FILLED';
  const SORT_CREATED_AT               = 'CREATED_AT desc';
  
  private $cinemaId                   = null;

  public function __construct($cinemaId = NULL) {
    $this->cinemaId = $cinemaId;
    parent::__construct();
  }

    public function configure() {
    if (!is_null($this->cinemaId)) {
      $arrScreenNo = CINEMATable::getInstance()->findScreenNumberArray($this->cinemaId);
    } else {
      $arrScreenNo = array('-- select a cinema --');
    }
    
    $arrStatusList = StringUtil::getStatusArray();
    $arrCinemaList = CINEMATable::getInstance()->findAllArray(sfContext::getInstance()->getUser()->getAttribute('merchant_id'), true);

    $widgets = array(
            self::FIELD_IS_MOVIE_NONEMPTY => new sfWidgetFormInputHidden(array(), array()),
            self::FIELD_OFFER_CODE        => new sfWidgetFormInput(array(), array()),
            self::FIELD_CINEMA            => new sfWidgetFormSelect(array('choices' => $arrCinemaList), array('multiple' => false, 'expand' => true)),
            self::FILED_SCREEN_NO         => new sfWidgetFormSelect(array('choices' => $arrScreenNo), array('multiple' => false, 'expand' => true)),   
            self::FIELD_MOVIE_TITLE       => new sfWidgetFormInput(array(), array()),
            self::FIELD_SESSION_TIME_D    => new sfWidgetFormInput(array(), array('maxlength' => 255)),
            self::FIELD_SESSION_TIME_T    => new sfWidgetFormTime(array('can_be_empty' => false), array()),
            self::FIELD_MOVIE_TRAILER_URL => new sfWidgetFormInput(array(), array()),
            self::FIELD_VALID_FROM_D      => new sfWidgetFormInput(array(), array('maxlength' => 255)),
            self::FIELD_VALID_FROM_T      => new sfWidgetFormTime(array('can_be_empty' => false), array()),
            self::FIELD_VALID_TO_D        => new sfWidgetFormInput(array(), array('maxlength' => 255)),
            self::FIELD_VALID_TO_T        => new sfWidgetFormTime(array('can_be_empty' => false), array()),
            self::FIELD_TICKET_PRICE      => new sfWidgetFormInput(array(), array('maxlength' => 255)),
            self::FIELD_SEATS_COUNT       => new sfWidgetFormInput(array(), array('maxlength' => 4)),
            self::FIELD_SEATS_FROM        => new sfWidgetFormInput(array(), array('maxlength' => 10)),
            self::FIELD_SEATS_TO          => new sfWidgetFormInput(array(), array('maxlength' => 10)),
            self::FIELD_CINEMA_NO         => new sfWidgetFormInput(array(), array('maxlength' => 20)),
            self::FIELD_ADDITIONAL_INFO   => new sfWidgetFormInput(array(), array('maxlength' => 30)),
            self::FIELD_STATUS            => new sfWidgetFormSelect(array('choices' => $arrStatusList), array('multiple' => false, 'expand' => true))
    );

    $labels = array(
            self::FIELD_OFFER_CODE        => 'Offer Code<req />',
            self::FIELD_CINEMA            => 'Cinema<req />',
            self::FILED_SCREEN_NO         => 'Screen Number',
            self::FIELD_MOVIE_TITLE       => 'Movie Title<req />',
            self::FIELD_SESSION_TIME_D    => 'Session Time<req />',
            self::FIELD_SESSION_TIME_T    => 'Session Time<req />',
            self::FIELD_MOVIE_TRAILER_URL => 'Trailer URL',
            self::FIELD_VALID_FROM_D      => 'Valid From<req />',
            self::FIELD_VALID_FROM_T      => 'Valid From<req />',
            self::FIELD_VALID_TO_D        => 'Valid To',
            self::FIELD_VALID_TO_T        => 'Valid To',
            self::FIELD_TICKET_PRICE      => 'Ticket Price (inc GST)<req />',
            self::FIELD_SEATS_COUNT       => 'No. of Tickets<req />',
            self::FIELD_SEATS_FROM        => 'Seat No. From',
            self::FIELD_SEATS_TO          => 'Seat No. To',
            self::FIELD_CINEMA_NO         => 'Cinema No.',
            self::FIELD_ADDITIONAL_INFO   => 'Special Offer',
            self::FIELD_STATUS            => 'Status<req />'
    );

    $this->setWidgets($widgets);
    $this->widgetSchema->setLabels($labels);

    $validators = array(
            self::FIELD_IS_MOVIE_NONEMPTY => new sfValidatorString(array(), array('required' => 'Please fetch Movie Information')),
            self::FIELD_OFFER_CODE        => new sfValidatorString(array(), array('required' => LangUtil::getText('error_required', array($labels[self::FIELD_OFFER_CODE])))),
            self::FIELD_SESSION_TIME_D    => new sfValidatorString(array(), array('required' => LangUtil::getText('error_required', array($labels[self::FIELD_SESSION_TIME_D])))),
            self::FIELD_SESSION_TIME_T    => new sfValidatorString(array(), array('required' => LangUtil::getText('error_required', array($labels[self::FIELD_SESSION_TIME_T])))),
            self::FIELD_CINEMA            => new sfValidatorString(array(), array('required' => LangUtil::getText('error_required', array($labels[self::FIELD_CINEMA])))),
            //self::FIELD_MOVIE_TRAILER_URL => new sfValidatorUrl(array(), array('required' => LangUtil::getText('error_required', array($labels[self::FIELD_MOVIE_TRAILER_URL])), 'invalid' => LangUtil::getText('error_invalid', array($labels[self::FIELD_MOVIE_TRAILER_URL])))),
            self::FIELD_VALID_FROM_D      => new sfValidatorString(array(), array('required' => LangUtil::getText('error_required', array($labels[self::FIELD_VALID_FROM_D])))),
            self::FIELD_VALID_FROM_T      => new sfValidatorString(array(), array('required' => LangUtil::getText('error_required', array($labels[self::FIELD_VALID_FROM_T])))),
            self::FIELD_TICKET_PRICE      => new sfValidatorNumber(array('required' => true), array('required' => LangUtil::getText('error_required', array($labels[self::FIELD_TICKET_PRICE])), 'invalid' => LangUtil::getText('error_invalid', array($labels[self::FIELD_TICKET_PRICE])))),
            self::FIELD_SEATS_COUNT       => new sfValidatorNumber(array('required' => true), array('required' => LangUtil::getText('error_required', array($labels[self::FIELD_SEATS_COUNT])), 'invalid' => LangUtil::getText('error_invalid', array($labels[self::FIELD_SEATS_COUNT])))),
            self::FIELD_STATUS            => new sfValidatorString(array(), array('required' => LangUtil::getText('error_required', array($labels[self::FIELD_STATUS]))))
    );

    $this->setValidators($validators);
    $this->validatorSchema->setPostValidator(new sfValidatorCallback(array('callback' => array($this, 'postValidator'))));

    $r = OFFERTable::getInstance()->findMaxId();
    $this->setDefault(self::FIELD_IS_MOVIE_NONEMPTY, '');
    $this->setDefault(self::FIELD_OFFER_CODE, StringUtil::generateOfferCode($r->maxId));
    $this->setDefault(self::FIELD_SESSION_TIME_D, date('Y-m-d'));
    $this->setDefault(self::FIELD_VALID_FROM_D, date('Y-m-d'));
    $this->setDefault(self::FIELD_VALID_FROM_T, date('H:i'));
    $this->setDefault(self::FIELD_VALID_TO_D, date('Y-m-d'));

    $this->widgetSchema->setNameFormat(self::FORM_NAME . '[%s]');

    $this->validatorSchema->setOption('allow_extra_fields', true);
    $this->validatorSchema->setOption('filter_extra_fields', false);
  }

  public function postValidator($validator, $values) { 
    $postedVals = $_POST[self::FORM_NAME];
    
    if (trim($values[self::FIELD_SESSION_TIME_D]) != '' && trim(self::convertTimeArray2String($postedVals[self::FIELD_SESSION_TIME_T])) != '') {
      if (!strtotime($values[self::FIELD_SESSION_TIME_D] . ' ' . self::convertTimeArray2String($postedVals[self::FIELD_SESSION_TIME_T]))) {
        $error = new sfValidatorError($validator, 'Session Time is invalid. Accepted format is YYYY-MM-DD HH:MM.');
        throw new sfValidatorErrorSchema($validator, array(self::FIELD_SESSION_TIME_D => $error));
      }
    }

    if (trim($values[self::FIELD_VALID_FROM_D]) != '' && trim(self::convertTimeArray2String($postedVals[self::FIELD_VALID_FROM_T])) != '') {
      if (!strtotime($values[self::FIELD_VALID_FROM_D] . ' ' . self::convertTimeArray2String($postedVals[self::FIELD_VALID_FROM_T]))) {
        $error = new sfValidatorError($validator, 'Valid From is invalid. Accepted format is YYYY-MM-DD HH:MM.');
        throw new sfValidatorErrorSchema($validator, array(self::FIELD_VALID_FROM_D => $error));
      }
    }

    if (trim($values[self::FIELD_VALID_TO_D]) != '' && trim(self::convertTimeArray2String($postedVals[self::FIELD_VALID_TO_T])) != '') {
      if (!strtotime($values[self::FIELD_VALID_TO_D] . ' ' . self::convertTimeArray2String($postedVals[self::FIELD_VALID_TO_T]))) {
        $error = new sfValidatorError($validator, 'Valid To is invalid. Accepted format is YYYY-MM-DD HH:MM.');
        throw new sfValidatorErrorSchema($validator, array(self::FIELD_VALID_TO_D => $error));
      }
    }

    if ((trim($values[self::FIELD_VALID_TO_D]) == '' || trim(self::convertTimeArray2String($postedVals[self::FIELD_VALID_TO_T])) == '') && (trim($postedVals[self::FIELD_SESSION_TIME_D]) == '' || trim(self::convertTimeArray2String($postedVals[self::FIELD_SESSION_TIME_T])) == '')) {
      $error = new sfValidatorError($validator, 'You must specify either Valid To or Session Time');
      throw new sfValidatorErrorSchema($validator, array(self::FIELD_VALID_TO_D => $error));
    }

    if (trim($values[self::FIELD_SEATS_COUNT]) != '' && trim($values[self::FIELD_TICKET_PRICE]) != '') {
      $ticketPrice = $values[self::FIELD_TICKET_PRICE] * $values[self::FIELD_SEATS_COUNT];
      if ($ticketPrice < 100) {
        $error = new sfValidatorError($validator, 'Minimum total ticket price allowed is $100.');
        throw new sfValidatorErrorSchema($validator, array(self::FIELD_TICKET_PRICE => $error));
      }
    }

    if (trim($values[self::FIELD_SESSION_TIME_D]) != '' && trim(self::convertTimeArray2String($postedVals[self::FIELD_SESSION_TIME_T])) != '') {
      if (strtotime($values[self::FIELD_SESSION_TIME_D] . ' ' . self::convertTimeArray2String($postedVals[self::FIELD_SESSION_TIME_T])) <= time()) {
        $error = new sfValidatorError($validator, 'Session Time should be a future date.');
        throw new sfValidatorErrorSchema($validator, array(self::FIELD_SESSION_TIME_D => $error));
      }
    }

    if (trim($values[self::FIELD_VALID_TO_D]) != '' && trim(self::convertTimeArray2String($postedVals[self::FIELD_VALID_TO_T])) != '' && trim($values[self::FIELD_VALID_FROM_D]) != '' && trim(self::convertTimeArray2String($postedVals[self::FIELD_VALID_FROM_T])) != '') {
      if (strtotime($values[self::FIELD_VALID_TO_D] . ' ' . self::convertTimeArray2String($postedVals[self::FIELD_VALID_TO_T])) <= strtotime($values[self::FIELD_VALID_FROM_D] . ' ' . self::convertTimeArray2String($postedVals[self::FIELD_VALID_FROM_T]))) {
        $error = new sfValidatorError($validator, 'Valid From should be prior to Valid To.');
        throw new sfValidatorErrorSchema($validator, array(self::FIELD_VALID_TO_D => $error));
      }
    }

    if (trim($values[self::FIELD_SESSION_TIME_D]) != '' && trim(self::convertTimeArray2String($postedVals[self::FIELD_SESSION_TIME_T])) != '' && trim($values[self::FIELD_VALID_FROM_D]) != '' && trim(self::convertTimeArray2String($postedVals[self::FIELD_VALID_FROM_T])) != '') {
      if (strtotime($values[self::FIELD_SESSION_TIME_D] . ' ' . self::convertTimeArray2String($postedVals[self::FIELD_SESSION_TIME_T])) <= strtotime($values[self::FIELD_VALID_FROM_D] . ' ' . self::convertTimeArray2String($postedVals[self::FIELD_VALID_FROM_T]))) {
        $error = new sfValidatorError($validator, 'Valid From should be prior to Session Time.');
        throw new sfValidatorErrorSchema($validator, array(self::FIELD_VALID_FROM_D => $error));
      }
    }

    $oneMonthFromNow = strtotime('+1 month');
    $sessionTimeTs = strtotime($values[self::FIELD_SESSION_TIME_D] . ' ' . self::convertTimeArray2String($postedVals[self::FIELD_SESSION_TIME_T]));
    $validFromTs = strtotime($values[self::FIELD_VALID_FROM_D] . ' ' . self::convertTimeArray2String($postedVals[self::FIELD_VALID_FROM_T]));
    $validToTs = strtotime($values[self::FIELD_VALID_TO_D] . ' ' . self::convertTimeArray2String($postedVals[self::FIELD_VALID_TO_T]));

    if (trim($values[self::FIELD_SESSION_TIME_D]) != '' && trim(self::convertTimeArray2String($postedVals[self::FIELD_SESSION_TIME_T])) != '' && $sessionTimeTs > $oneMonthFromNow) {
      $error = new sfValidatorError($validator, 'Session Time should be less than a month from today.');
      throw new sfValidatorErrorSchema($validator, array(self::FIELD_SESSION_TIME_D => $error));
    }
    if (trim($values[self::FIELD_VALID_FROM_D]) != '' && trim(self::convertTimeArray2String($postedVals[self::FIELD_VALID_FROM_T])) != '' && $validFromTs > $oneMonthFromNow) {
      $error = new sfValidatorError($validator, 'Valid From should be less than a month from today.');
      throw new sfValidatorErrorSchema($validator, array(self::FIELD_VALID_FROM_D => $error));
    }
    if (trim($values[self::FIELD_VALID_TO_D]) != '' && trim(self::convertTimeArray2String($postedVals[self::FIELD_VALID_TO_T])) != '' && $validToTs > $oneMonthFromNow) {
      $error = new sfValidatorError($validator, 'Valid To should be less than a month from today.');
      throw new sfValidatorErrorSchema($validator, array(self::FIELD_VALID_TO_D => $error));
    }

    return $values;
  }

  public function populateData(OFFER $offer) {
    $this->setDefault(self::FIELD_IS_MOVIE_NONEMPTY, 1);
    if (!$offer->isNew()) {
      $this->setDefault(self::FIELD_OFFER_CODE, $offer->getCode());
    }
    $this->setDefault(self::FIELD_CINEMA, $offer->getCinemaId());
    $this->setDefault(self::FILED_SCREEN_NO, $offer->getScreenNumber());
    $this->setDefault(self::FIELD_MOVIE_TITLE, $offer->getMOVIE()->getTitle());
    $this->setDefault(self::FIELD_MOVIE_TRAILER_URL, $offer->getMOVIE()->getUrlTrailer());
    @list($d, $t) = explode(' ', $offer->getMerchantsValidFrom());
    $this->setDefault(self::FIELD_VALID_FROM_D, $d);
    $this->setDefault(self::FIELD_VALID_FROM_T, $t);
    @list($d, $t) = explode(' ', $offer->getMerchantsValidTo());
    $this->setDefault(self::FIELD_VALID_TO_D, $d);
    $this->setDefault(self::FIELD_VALID_TO_T, $t);
    @list($d, $t) = explode(' ', $offer->getMerchantsSessionTime());
    $this->setDefault(self::FIELD_SESSION_TIME_D, $d);
    $this->setDefault(self::FIELD_SESSION_TIME_T, $t);
    $this->setDefault(self::FIELD_TICKET_PRICE, $offer->getTicketPrice());
    $this->setDefault(self::FIELD_SEATS_COUNT, $offer->getSeatsCount());
    $this->setDefault(self::FIELD_SEATS_FROM, $offer->getSeatsFrom());
    $this->setDefault(self::FIELD_SEATS_TO, $offer->getSeatsTo());
    $this->setDefault(self::FIELD_CINEMA_NO, $offer->getCinemaNo());
    $this->setDefault(self::FIELD_ADDITIONAL_INFO, $offer->getAdditionalInfo());
    $this->setDefault(self::FIELD_STATUS, $offer->getStatus());
  }
  
  public static function convertTimeArray2String($arr) {
    $hour = isset($arr['hour']) ? $arr['hour'] : '00';
    $minute = isset($arr['minute']) ? $arr['minute'] : '00';
    $seconds = '00';
    
    return $hour.':'.$minute.':'.$seconds;
  }
}

?>